<template>
    <div class="role-list">
        <div class="move-box">
            <RiskLeftModule
                v-model="userValue"
                @on-submit="submitInput"
                @on-handleNode="clickNode"
                :placeholders="ltitleName"
                :treeData="treeData"
                :leftHeight="leftHgt"
                :currentKey="2"
            >
                <template slot="ltitle">角色维护</template>
            </RiskLeftModule>

            <!-- 角色维护 -->
            <template v-if="cutInfo === '本地' || cutInfo === '外部'">
                <RiskRightModule
                    v-model="roleParams.keyOrName"
                    :rightPlace="rtitleName"
                    :rightHeight="leftHgt"
                    @on-keyup="selectRoleData"
                    :style="{ height: 'calc(100vh - 40px)' }"
                >
                    <p slot="rtitle">角色维护</p>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" @click="selectRoleData">查询</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-if="cutInfo === '本地'" @click="dialogAddRole = true" v-authCode.show="B_0217">
                            新增
                        </el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" @click="downLoadRoleFile" v-authCode.show="B_0218">导出</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="danger" size="mini" v-if="cutInfo === '本地'" @click="lookDeleteRole" v-authCode.show="B_0216"
                            >删除</el-button
                        >
                    </span>
                    <slot>
                        <RiskTableP
                            ref="risk-table"
                            :tableConfig="tableConfig"
                            :tableData="tableData"
                            :column="tableColumns"
                            :searchParams="roleParams"
                            v-loading="tableLoading"
                            :paging="role"
                            @page-change="getRoleTableData"
                            @getAllData="getAllData"
                            class="tableContent"
                            :key="roleTableKey"
                        >
                            <template #roleCode="{ row }">
                                <span v-if="['2', '4', '5'].includes(row.modifyType) && row.modifyStatus === '1'">
                                    <i class="el-icon-setting" />{{ row.roleCode }}
                                </span>
                                <span v-else-if="row.modifyType === '3' && row.modifyStatus === '1'">
                                    <i class="el-icon-delete" />{{ row.roleCode }}
                                </span>
                                <span v-else-if="row.modifyType === '1' && row.modifyStatus === '1'">
                                    <i class="el-icon-folder-add" />{{ row.roleCode }}
                                </span>
                                <span v-else>
                                    {{ row.roleCode }}
                                </span>
                            </template>
                            <template #operation="{ row }">
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-edit"
                                    topTitle="编辑角色"
                                    v-authCode="B_0215"
                                    :disabled="row.modifyType == '3' && row.modifyStatus === '1'"
                                    v-if="cutInfo === '本地'"
                                    @on-click="lookEditRow(row)"
                                ></RiskIconButton>
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-setting"
                                    topTitle="菜单权限"
                                    v-authCode="B_0310"
                                    :disabled="row.modifyType == '3' && row.modifyStatus === '1'"
                                    @on-click="openMenuTree(row)"
                                ></RiskIconButton>
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-printer"
                                    v-authCode="B_0375"
                                    topTitle="角色修改记录"
                                    v-if="cutInfo === '本地'"
                                    size="mini"
                                    @on-click="operateRecord(row.roleCode)"
                                ></RiskIconButton>
                                <RiskIconButton
                                    type="danger"
                                    v-authCode="B_0216"
                                    icon="el-icon-delete"
                                    topTitle="删除角色"
                                    :disabled="row.modifyStatus == '1' || row.roleCode === 'YH0000'"
                                    v-if="cutInfo === '本地'"
                                    @on-click="lookRole(row)"
                                ></RiskIconButton>
                            </template>
                        </RiskTableP>
                    </slot>
                </RiskRightModule>
                <!-- 新增 -->
                <yh-dialog drag title="新增角色" :visible.sync="dialogAddRole" width="400px" v-loading="loading" :close-on-click-modal="false">
                    <el-form label-width="140" size="mini">
                        <el-form-item label="角色编号">
                            <el-input placeholder="自动生成" style="width: 220px" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="角色名称">
                            <el-input style="width: 220px" v-model="roleName" maxlength="50" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="条目权限">
                            <el-select style="width: 220px" v-model="entryRoleCode" clearable>
                                <el-option
                                    v-for="(item, key) in pojoTransFormList(entryRoles)"
                                    :key="key"
                                    :value="item.dictKey"
                                    :label="item.dictKey + ' ' + item.dictKeyName"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="dialogAddRole = false"> 取 消 </el-button>
                        <el-button size="mini" type="primary" @click="addRoleData"> 确 定 </el-button>
                    </div>
                </yh-dialog>
                <!-- 编辑 -->
                <div>
                    <yh-dialog drag title="编辑角色" :visible.sync="dialogEditRole" width="400px" v-loading="loading" :close-on-click-modal="false">
                        <el-form label-width="140" size="mini">
                            <el-form-item label="角色编号">
                                <el-input placeholder="自动生成" style="width: 220px" v-model="editRole.roleCode" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="角色名称">
                                <el-input style="width: 220px" v-model="editRole.roleName" maxlength="50" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="条目权限">
                                <el-select style="width: 220px" v-model="editRole.entryRoleCode" clearable>
                                    <el-option
                                        v-for="(item, key) in pojoTransFormList(entryRoles)"
                                        :key="key"
                                        :value="item.dictKey"
                                        :label="item.dictKey + ' ' + item.dictKeyName"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="dialogEditRole = false"> 取 消 </el-button>
                            <el-button size="mini" type="primary" @click="editRoleData"> 确 定 </el-button>
                        </div>
                    </yh-dialog>
                </div>
                <!-- 删除 -->
                <div>
                    <yh-dialog
                        drag
                        title="确定删除角色？"
                        :visible.sync="removeRoleList"
                        width="500px"
                        v-loading="loading"
                        :close-on-click-modal="false"
                    >
                        <div class="remove-text">
                            <span>{{ roleCodeList.join(' , ') }}</span>
                        </div>
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="removeRoleList = false"> 取 消 </el-button>
                            <el-button size="mini" type="primary" @click="removeRole">确 定 </el-button>
                        </div>
                    </yh-dialog>
                </div>
            </template>

            <!-- 人员明细 -->
            <template v-else>
                <RiskRightModule v-model="person" :rightPlace="right2Place" :rightHeight="leftHgt">
                    <p slot="rtitle">人员明细</p>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" @click="selectData">查询</el-button>
                    </span>
                    <!-- <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0220" @click="roleBinding">角色绑定</el-button>
                    </span> -->
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" @click="putExlUser" v-authCode.show="B_0221">导出</el-button>
                    </span>
                    <!-- <span slot="button" class="dict-r-slot">
                        <el-button type="danger" size="mini" v-authCode.show="B_0222" @click="openUserRemov">删除</el-button>
                    </span> -->
                    <slot>
                        <el-table
                            :data="roleData"
                            border
                            size="mini"
                            style="width: 100%"
                            height="calc(100vh - 175px)"
                            @selection-change="handleSelectionUser"
                            :header-cell-style="{ 'text-align': 'center' }"
                        >
                            <RiskTableSelection
                                row-key="userCode"
                                :current-page-table-list="roleData"
                                :selected="userCodeList"
                                show-drop-down
                                @dropdown-click="userDropdownClick"
                            />
                            <!--<el-table-column type="selection" width="55" size="mini"> </el-table-column>-->
                            <el-table-column prop="userName" label="用户账号"> </el-table-column>
                            <el-table-column prop="userNickName" label="用户昵称"> </el-table-column>
                            <el-table-column prop="deptName" label="部门">
                                <template slot-scope="scope">
                                    {{ scope.row.deptName ? scope.row.deptName : '--' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="createDate" label="创建日期" :formatter="formatterDate" align="center"> </el-table-column>
                        </el-table>
                        <div class="block">
                            <risk-pagination :paging="detail" @page-change="detailChange"></risk-pagination>
                        </div>
                    </slot>
                </RiskRightModule>
                <!-- 删除用户 -->
                <div>
                    <yh-dialog
                        drag
                        title="确定删除用户？"
                        :visible.sync="removeUserList"
                        width="500px"
                        v-loading="editLoading"
                        :close-on-click-modal="false"
                    >
                        <div class="remove-text">
                            <span> {{ userNameList.join(' , ') }}</span>
                        </div>
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="removeUserList = false"> 取 消 </el-button>
                            <el-button size="mini" type="primary" @click="removeUser">确 定 </el-button>
                        </div>
                    </yh-dialog>
                </div>
                <!-- 角色绑定 -->
                <div>
                    <yh-dialog drag :title="roleTitle" :visible.sync="roleUserDialog" width="800px" v-loading="loading" :close-on-click-modal="false">
                        <div style="height: 450px">
                            <RiskTrantable
                                v-if="roleUserDialog"
                                leftPlaceholder="用户账号/昵称/部门"
                                :leftColumns="tranColumns"
                                :rightColumns="tranColumns"
                                :leftTableData="leftTranData"
                                :rightTableData="rightTranData"
                                :leftSearchNames="['userName', 'userNickName', 'deptName']"
                                indexKey="userCode"
                                ref="tranTable"
                                sort="userName"
                            />
                        </div>
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="roleUserDialog = false"> 取 消 </el-button>
                            <el-button size="mini" type="primary" @click="submitRoleBinding">确 定 </el-button>
                        </div>
                    </yh-dialog>
                </div>
            </template>
        </div>
        <UserResourceTree
            :visible.sync="treeVisible"
            :code="treeCode"
            :serialNo="currentRoleInfo.serialNo"
            @menu-setting="menuSetting"
            :isDisabled="cutInfo === '外部'"
        />
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { getCurrentPageData, dateFormat, timeFormat } from '@/utils/tools';
import { downLoadFile } from '@/utils/request';

import RiskLeftModule from '@/common/components/risk-left-module.vue';
import RiskRightModule from '@/common/components/risk-right-module.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTrantable from '@/common/components/risk-trantable.vue';
import UserResourceTree from '@/pages/system-maintence/auth-manage/user-resource-tree.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import { ColumnVO, TableConfigVO, VueObject } from '@/common/vo';
import DictionConstUtil from '@/utils/diction-const-util';
import Dict from '../dict/role-check';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import RiskEmitter from '@/common/mixis/risk-emitter.vue';
import { mixins } from 'vue-class-component';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'RoleList',
    components: {
        RiskLeftModule,
        RiskRightModule,
        RiskIconButton,
        RiskTrantable,
        UserResourceTree,
        RiskPagination,
        RiskTableP,
    },
})
export default class RoleList extends mixins(RiskEmitter) {
    private userValue: string = '';
    private ltitleName: string = '编号/名称';
    private leftHgt: string = 'calc(100vh - 40px)';
    private rtitleName: string = '角色编号/名称';
    private right2Place: string = '用户账号/昵称/部门';
    private roleParams: any = {
        keyOrName: '',
        sourceTypes: ['2'],
        sort: {
            field: '',
            order: '',
        },
    };
    roleTableKey: number = -1;
    private person: string = '';
    private dialogAddRole: boolean = false;
    private roleName: string = '';
    private entryRoleCode: string = ''; // 条目权限

    private roleCodeList = [];
    private userNameList = [];
    private userCodeList = [];
    private treeData: any = [
        {
            label: '本地',
            id: 1,
            children: [],
        },
        {
            label: '外部',
            id: 2,
            children: [],
        },
    ];
    private cutInfo: string = '外部';
    private roleId: string = '';
    private roleTitle: string = '';
    private cutBool: boolean = true;
    private tableData = [
        // {
        //     roleCode: '',
        //     roleName: '',
        //     sourceType: '',
        //     createUser: '',
        //     modifyUser: '',
        //     createDate: null,
        //     createTime: null,
        // },
    ];
    private roleData = [
        {
            userName: '',
            userNickName: '',
            deptName: '',
            createDate: '',
        },
    ];
    private roleDataList: [];
    private roleDataLists: any[] = [
        {
            lastAccessTime: '',
            superuser: '',
            userCode: '',
            userName: '',
        },
    ];
    private tableDisk = [];
    private tableSans = [];
    private tableDiskList = [];
    private tableSansList = [];
    private loading: boolean = false;
    private removeRoleList: boolean = false;
    private dialogEditRole: boolean = false;
    private removeUserList: boolean = false;
    private role: pages = {
        total: 0,
        pageSize: 25,
        currentPage: 1,
    };
    private detail: pages = {
        total: 0,
        pageSize: 25,
        currentPage: 1,
    };
    private editRole = {
        roleCode: '',
        roleName: '',
        entryRoleCode: '',
        key: '',
    };
    private roleUserDialog: boolean = false;

    // 穿梭框数据
    private tranColumns: any[] = [
        {
            label: '名称',
            prop: 'userCode',
            width: 70,
            hidden: true,
        },
        {
            label: '用户账号',
            prop: 'userName',
            width: 90,
        },
        {
            label: '昵称',
            prop: 'userNickName',
            width: 90,
        },
        {
            label: '部门',
            prop: 'deptName',
            width: null,
        },
    ];
    private leftTranData: any[] = [
        {
            id: '',
            userName: '',
            lastAccessTime: '',
            superuser: false,
            userCode: '',
        },
    ];

    private rightTranData: any[] = [
        {
            id: '',
            lastAccessTime: '',
            superuser: false,
            userCode: '',
            userName: '',
        },
    ];
    private roleIdList: any[] = [];

    // 条目权限参数类型
    private entryRoles = {
        '001': '风控',
        '002': '投资',
        '003': '交易',
        '004': '合规风险',
    };

    // 权限树形菜单
    private treeVisible = false;
    private treeCode = '';
    currentRoleInfo: any = {};
    tableLoading: boolean = false;
    // 字典
    Dict = new Dict();
    tableConfig: TableConfigVO = {
        rowKey: 'roleCode',
        allRowKeys: [],
    };
    tableColumns: ColumnVO[] = [
        {
            type: 'checkbox',
            selectedAll: true,
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        { field: 'roleCode', title: '角色编号', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        { field: 'roleName', title: '角色名称', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        {
            field: 'entryRoleCode',
            title: '条目权限',
            align: 'center',
            sortable: true,
            minWidth: '120px',
            filterType: 'funnel',
            filterField: 'entryRoleCodes',
            filters: DictionConstUtil.PojoToList3(this.Dict.entryRoleCodePojo),
            render: value => this.getArranyData(value),
        },
        {
            field: 'sourceType',
            title: '数据来源',
            align: 'center',
            sortable: true,
            minWidth: '120px',
            filterType: 'funnel',
            filterField: 'sourceTypes',
            filters: DictionConstUtil.PojoToList3(this.Dict.sourceTypePojo),
            render: value => this.Dict.sourceTypePojo[value],
        },
        { field: 'createUser', title: '创建人', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] }, //
        {
            field: 'createDate',
            title: '创建时间',
            align: 'center',
            sortable: true,
            minWidth: '180px',
            render: (value, row) => (dateFormat(value) + ' ' + timeFormat(row.createTime)).trim(),
        },
        { field: 'modifyUser', title: '更新人', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        {
            field: 'modifyDate',
            title: '更新时间',
            align: 'center',
            sortable: true,
            minWidth: '180px',
            render: (value, row) => (dateFormat(value) + ' ' + timeFormat(row.modifyTime)).trim(),
        },
        { field: 'operation', fixed: 'right', title: '操作', align: 'center', width: '200px' },
    ];

    mounted() {
        this.getRoleInfo();
    }

    // 格式化日期
    formatterDate(row, column, cellValue) {
        return cellValue ? dateFormat(cellValue) : '';
    }

    //  格式化时间
    formatterTime(row, column, cellValue) {
        return cellValue ? timeFormat(cellValue) : '';
    }

    /**
     * 对象转集合
     */
    pojoTransFormList = param => {
        let list = [];
        for (let key in param) {
            list.push({ dictKey: key, dictKeyName: param[key] });
        }
        return list;
    };

    private filterHandler(name: string): boolean {
        return true;
    }

    // 判断是否有删除的角色
    private lookDeleteRole(): void {
        this.roleCodeList = (this.$refs['risk-table'] as any).checkRowKeys;
        if (!this.roleCodeList || this.roleCodeList.length < 1) {
            this.yh_message_warn('请选择删除的角色');
            return;
        }
        this.removeRoleList = true;
    }

    // 左边查询
    private submitInput(): void {}

    // 左边栏选择节点
    private clickNode(data: any): void {
        this.cutInfo = data.label;
        this.roleId = data.id;
        this.roleTitle = '角色' + data.id + '人员绑定';
        if (['本地', '外部'].includes(this.cutInfo)) {
            // 切换时重新请求置空请求参数  TODO
            this.roleParams = {
                keyOrName: '',
                sourceTypes: this.cutInfo == '本地' ? ['1'] : ['2'],
                sort: {
                    field: '',
                    order: '',
                },
            };
            this.role.currentPage = 1;
            this.roleTableKey++;
            this.getRoleTableData();
        } else {
            this.getQueryList(this.roleId); // 重置节点数据
        }
    }

    getArranyData(val: any) {
        if (val) {
            let vals = val.split(',');
            let nameList = [];
            for (let i = 0; i < vals.length; i++) {
                nameList.push(this.entryRoles[vals[i]]);
            }
            return nameList.join(',');
        } else {
            return '';
        }
    }

    // 获取数据
    private getRoleInfo(): void {
        this.$axios.get('/role/query/all').then((res: any) => {
            var local = [];
            var outside = [];
            let disk = [];
            let Sans = [];
            for (let item of res) {
                if (item.sourceType === '1') {
                    disk.push(item);
                    let datas = item.roleCode + '-' + item.roleName;
                    local.push({ label: datas, id: item.roleCode });
                } else {
                    Sans.push(item);
                    let datas = item.roleCode + '-' + item.roleName;
                    outside.push({ label: datas, id: item.roleCode });
                }
            }
            this.treeData[0].children = local;
            this.treeData[1].children = outside;
            this.tableDisk = disk;
            this.tableSans = Sans;
            this.tableDiskList = disk;
            this.tableSansList = Sans;
            this.role.currentPage = 1;
            this.getRoleTableData();
        });
    }

    // 人员明细
    private getQueryList(roleId: string): void {
        this.$axios.get('/role/user/query/' + roleId).then((res: any) => {
            if (res) {
                this.roleDataLists = res;
                let resList = res;
                for (let i = 0; i < resList.length; i++) {
                    resList[i].id = resList[i].userCode;
                }
                this.rightTranData = resList;
                this.roleDataList = res;
                this.roleData = getCurrentPageData(this.roleDataList, this.detail.currentPage, this.detail.pageSize);
                this.detail.total = this.roleDataList.length;
            }
        });
    }

    // 人员分页
    private detailChange(): void {
        this.roleData = getCurrentPageData(this.roleDataList, this.detail.currentPage, this.detail.pageSize);
    }

    // 全选角色
    dropdownClick(command: string) {
        if (command === 'all') {
            this.roleCodeList = this.tableDisk.map(item => item.roleCode);
        }
    }

    // 新增
    private addRoleData(): void {
        if (!this.roleName) {
            this.yh_message_error('角色名称不能为空');
            return;
        }
        if (!this.entryRoleCode) {
            this.yh_message_error('条目权限不能为空');
            return;
        }

        this.loading = true;
        this.$axios
            .post('/role/insert/one', {
                roleCode: '自动生成',
                sourceType: '1',
                roleName: this.roleName,
                entryRoleCode: this.entryRoleCode,
            })
            .then(res => {
                this.loading = false;
                this.dialogAddRole = false;
                this.getRoleInfo();
                this.refreshTable();
                this.yh_message_success('添加成功');
                this.roleName = '';
                this.entryRoleCode = '';
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 查看修改记录
    lookRow(row: any) {
        // TODO
    }

    // 判断  在复核状态中仍可编辑等操作，但不可删除
    judgeModifyStatus(val) {
        if (val.modifyStatus == '1') {
            // this.editCheckTip = true;
            return true;
        }
        return false;
    }

    judgeDialog() {
        let pro = this.$confirm(` <div style="text-align:center">已存在未复核记录，确定要修改吗？</div>`, '提示', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            showClose: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
        });
        return pro;
    }
    // 查看编辑信息
    private lookEditRow(row: any): void {
        if (this.judgeModifyStatus(row)) {
            const pro = this.judgeDialog();
            pro.then(() => {
                this.lookEditRowReal(row);
            });
        } else {
            this.lookEditRowReal(row);
        }
    }

    lookEditRowReal(row: any): void {
        // this.editRole = {
        //     key: row.key,
        //     roleCode: row.roleCode,
        //     roleName: row.roleName,
        //     entryRoleCode: row.entryRoleCode,
        // };
        this.editRole = JSON.parse(JSON.stringify(row));
        this.editRole.key = row.roleCode;
        this.dialogEditRole = true;
    }

    // 编辑
    private editRoleData(): void {
        let data = this.editRole;
        if (!data.roleName) {
            this.yh_message_error('角色名称不能为空');
            return;
        }
        if (!data.entryRoleCode) {
            this.yh_message_error('条目权限不能为空');
            return;
        }

        this.loading = true;
        this.$axios({
            url: '/role/update/one',
            method: 'put',
            data: data,
        })
            .then(res => {
                this.loading = false;
                this.dialogEditRole = false;
                this.getRoleInfo();
                this.refreshTable();
                this.yh_message_success('编辑成功');
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 查看单个删除id
    private lookRole(row: any): void {
        this.removeRoleList = true;
        this.roleCodeList = [];
        this.roleCodeList.push(row.roleCode);
    }

    // 删除角色
    private removeRole(): void {
        this.loading = true;
        this.$axios({
            url: '/role/delete',
            method: 'DELETE',
            data: this.roleCodeList,
        })
            .then(res => {
                this.loading = false;
                this.removeRoleList = false;
                this.getRoleInfo();
                this.refreshTable();
                this.yh_message_success('删除成功');
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 查询角色
    private selectRoleData(): void {
        // this.tableDisk = this.handleFilter(this.tableDiskList, this.roleParams.keyOrName);
        // this.role.total = this.tableDisk.length;
        // this.tableData = getCurrentPageData(this.tableDisk, this.role.currentPage, this.role.pageSize);
        this.role.currentPage = 1;
        this.getRoleTableData();
        this.yh_message_success('查询成功');
    }

    // // 角色筛选数据
    // private handleFilter(dataSource: any, param: any): any {
    //     if (!param || !dataSource) {
    //         return dataSource;
    //     } else {
    //         return dataSource.filter(
    //             (item: any) =>
    //                 (item.roleName || '').toUpperCase().includes(param.toUpperCase()) ||
    //                 (item.roleCode || '').toUpperCase().includes(param.toUpperCase())
    //         );
    //     }
    // }

    // 查詢人員明顯
    private selectData(): void {
        this.roleDataList = this.detailFileter(this.roleDataLists, this.person);
        this.detail.total = this.roleDataList.length;
        this.detail.currentPage = 1;
        this.roleData = getCurrentPageData(this.roleDataList, this.detail.currentPage, this.detail.pageSize);
        this.yh_message_success('查询成功');
    }

    // 人员明细过滤数据
    private detailFileter(dataSource: any, param: any): any {
        if (!param || !dataSource) {
            return dataSource;
        } else {
            return dataSource.filter(
                (item: any) =>
                    (item.userName || '').toUpperCase().includes(param.toUpperCase()) ||
                    (item.userNickName || '').toUpperCase().includes(param.toUpperCase()) ||
                    (item.deptName || '').toUpperCase().includes(param.toUpperCase())
            );
        }
    }

    // 角色分页
    private getRoleTableData($event?: any): void {
        if ($event && $event.type == 'sort') {
            this.roleParams.sort = {
                field: $event['sortField'],
                order: $event['order'],
            };
        }
        this.tableLoading = true;
        this.$axios
            .post('/role/query', { ...this.roleParams, paging: this.role })
            .then((res: any) => {
                this.role.total = res.total;
                this.tableData = res.list;
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }

    // 导出角色
    private downLoadRoleFile(): void {
        this.roleCodeList = (this.$refs['risk-table'] as any).checkRowKeys;
        let sourceType = this.cutInfo == '本地' ? '1' : '2';
        downLoadFile({
            url: '/role/export',
            method: 'post',
            data: { sourceTypes: [sourceType], rowSelection: this.roleCodeList, sort: this.roleParams.sort },
        });
    }

    // 选择用户
    private handleSelectionUser(val: any): void {
        this.userCodeList = [];
        this.userNameList = [];
        for (var i in val) {
            this.userCodeList.push(val[i].userCode);
            // this.userNameList.push(val[i].userName);
        }
    }

    // 导出用户
    private putExlUser(): void {
        // if (!this.userCodeList || this.userCodeList.length < 1) {
        //     this.yh_message_warn('请选择导出的人员');
        //     return;
        // }
        downLoadFile({
            url: '/role/user/export/' + this.roleId,
            method: 'post',
            data: this.userCodeList,
        });
    }

    // 全选用户
    userDropdownClick(command: string) {
        this.userCodeList.splice(0);
        this.userNameList.splice(0);
        if (command === 'all') {
            this.userCodeList = this.roleDataList.map((item: any) => item.userCode);
            // this.userNameList = this.roleDataList.map(item => item.userName);
        }
    }

    // 查看要删除的用户
    private openUserRemov(): void {
        this.userNameList = [];
        console.log(this.userCodeList, this.userNameList);
        if (this.userCodeList.length > 0) {
            for (let i = 0; i < this.userCodeList.length; i++) {
                for (let j = 0; j < this.roleDataLists.length; j++) {
                    if (this.roleDataLists[j].userCode === this.userCodeList[i]) {
                        this.userNameList.push(this.roleDataLists[j].userName);
                    }
                }
            }
        }
        if (!this.userCodeList || this.userCodeList.length < 1) {
            this.yh_message_warn('请选择删除的用户');
            return;
        }
        this.removeUserList = true;
    }

    // 删除用户
    private removeUser(): void {
        this.loading = true;
        this.$axios({
            url: '/role/user/delete/' + this.roleId,
            method: 'DELETE',
            data: this.userCodeList,
        })
            .then(res => {
                this.loading = false;
                this.removeUserList = false;
                this.getQueryList(this.roleId);
                this.yh_message_success('删除成功');
                this.userCodeList = [];
                this.userNameList = [];
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 查看角色绑定信息
    private roleBinding(): void {
        this.roleUserDialog = true;
        this.$axios
            .post('/role/user/query/all', {
                paging: {
                    total: 0,
                    currentPage: 1,
                    totalPage: 0,
                    pageSize: 10000,
                },
                keyName: '',
                filterCodes: this.roleDataLists.map((item: any) => item.userCode),
            })
            .then((res: any) => {
                let a = res.list;
                for (let i = 0; i < a.length; i++) {
                    a[i].id = a[i].userCode;
                }
                this.leftTranData = a;
            });
    }

    // 绑定角色
    private submitRoleBinding(): void {
        this.loading = true;
        this.roleIdList = [];
        const rightData = (this.$refs.tranTable as any).getRightAllData();
        rightData.map((item: any) => {
            this.roleIdList.push(item.userCode);
        });
        this.$axios
            .post('/role/user/relation/update/' + this.roleId, this.roleIdList)
            .then(res => {
                this.loading = false;
                this.roleUserDialog = false;
                this.yh_message_success('绑定成功');
                this.getQueryList(this.roleId);
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 打开菜单权限
    openMenuTree(val: any) {
        if (this.judgeModifyStatus(val)) {
            const pro = this.judgeDialog();
            pro.then(() => {
                this.openMenuTreeReal(val);
            });
        } else {
            this.openMenuTreeReal(val);
        }
    }

    openMenuTreeReal(row) {
        const key = row.roleCode;
        console.log(key);
        this.treeVisible = true;
        this.treeCode = key;
        this.currentRoleInfo = row;
    }

    // 菜单权限设置回调
    menuSetting() {
        this.getRoleTableData();
        this.refreshTable();
    }
    // 用户修改记录
    operateRecord(code: string) {
        this.dispatch('RoleManage', 'addTabs', { roleCode: code });
    }
    // 全选
    getAllData() {
        // TODO
        let data;
        if (this.cutInfo == '本地') {
            data = this.tableDiskList;
        } else {
            data = this.tableSansList;
        }
        this.tableConfig.allRowKeys = data.map(item => item.roleCode);
        (this.$refs['risk-table'] as any).handleSelectAll();
    }

    // 刷新表格
    refreshTable() {
        this.$emit('refresh-list');
    }
}
</script>
<style lang="scss" scoped>
.role-list {
    position: relative;

    .dict-r-slot {
        margin-left: 10px;
    }

    & /deep/ .el-dialog .el-dialog__body {
        max-height: 70vh;
    }
}
.tableContent {
    height: calc(100% - 75px) !important;
    /deep/ .vxe-table {
        .vxe-table--body-wrapper.body--wrapper {
            height: calc(100vh - 211px) !important;
        }
    }
}
.el-icon-setting {
    color: green;
    margin-right: 5px;
}

.el-icon-delete {
    color: red;
    margin-right: 5px;
}

.el-icon-folder-add {
    color: green;
    margin-right: 5px;
}
</style>
